package com.wanwanbookstore.servlet;

import com.wanwanbookstore.dao.BookDAO;
import com.wanwanbookstore.dao.BookCategoryDAO;
import com.wanwanbookstore.dao.OrderDAO;
import com.wanwanbookstore.dao.UserDAO;
import com.wanwanbookstore.entity.Book;
import com.wanwanbookstore.entity.BookCategory;
import com.wanwanbookstore.entity.Order;
import com.wanwanbookstore.entity.User;
import java.util.List;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class AdminServlet extends HttpServlet {
    private BookDAO bookDAO = new BookDAO();
    private BookCategoryDAO categoryDAO = new BookCategoryDAO();
    private OrderDAO orderDAO = new OrderDAO();
    private UserDAO userDAO = new UserDAO();

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 检查是否为管理员登录
        HttpSession session = request.getSession();
        Boolean isAdmin = (Boolean) session.getAttribute("isAdmin");
        if (isAdmin == null || !isAdmin) {
            response.sendRedirect("login.jsp");
            return;
        }

        String action = request.getParameter("action");
        if (action == null) {
            action = "list";
        }

        switch (action) {
            case "list":
                listBooks(request, response);
                break;
            case "edit":
                editBook(request, response);
                break;
            case "delete":
                deleteBook(request, response);
                break;
            case "add":
                showAddBookForm(request, response);
                break;
            case "orderList":
                listOrders(request, response);
                break;
            case "userList":
                listUsers(request, response);
                break;
            case "deletedUserList":
                listDeletedUsers(request, response);
                break;
            default:
                listBooks(request, response);
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        
        // 检查是否为管理员登录
        HttpSession session = request.getSession();
        Boolean isAdmin = (Boolean) session.getAttribute("isAdmin");
        if (isAdmin == null || !isAdmin) {
            response.sendRedirect("login.jsp");
            return;
        }

        String action = request.getParameter("action");
        if (action == null) {
            action = "list";
        }

        switch (action) {
            case "search":
                searchBooks(request, response);
                break;
            case "update":
                updateBook(request, response);
                break;
            case "save":
                saveBook(request, response);
                break;
            case "addCategory":
                addCategory(request, response);
                break;
            case "updateCategoryRecommendedStatus":
                updateCategoryRecommendedStatus(request, response);
                break;
            case "updateOrderStatus":
                updateOrderStatus(request, response);
                break;
            case "searchUsers":
                searchUsers(request, response);
                break;
            case "restoreUser":
                restoreUser(request, response);
                break;
            default:
                listBooks(request, response);
        }
    }

    // 列出所有图书（管理端）
    private void listBooks(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int page = 1;
        int pageSize = 10;

        if (request.getParameter("page") != null) {
            try {
                page = Integer.parseInt(request.getParameter("page"));
                if (page < 1) page = 1;
            } catch (NumberFormatException e) {
                page = 1;
            }
        }

        List<Book> books = bookDAO.getAllBooks(page, pageSize);
        int totalBooks = bookDAO.getAllBooksCount();
        int totalPages = (int) Math.ceil((double) totalBooks / pageSize);
        
        // 获取所有图书分类
        List<BookCategory> categories = categoryDAO.getAllCategories();
        
        // 获取推荐的分类
        List<BookCategory> recommendedCategories = categoryDAO.getRecommendedCategories();
        
        // 获取推荐分类的数量
        int recommendedCount = categoryDAO.getRecommendedCategoriesCount();
        
        // 获取每个分类的图书数量，存储在request中供JSP页面使用
        // 这里我们在JSP页面中直接使用BookDAO的方法来获取

        request.setAttribute("books", books);
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("totalBooks", totalBooks);
        request.setAttribute("categories", categories);
        request.setAttribute("recommendedCategories", recommendedCategories);
        request.setAttribute("recommendedCount", recommendedCount);

        request.getRequestDispatcher("admin.jsp").forward(request, response);
    }

    // 搜索图书
    private void searchBooks(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int page = 1;
        int pageSize = 10;
        String keyword = request.getParameter("keyword");

        if (request.getParameter("page") != null) {
            try {
                page = Integer.parseInt(request.getParameter("page"));
                if (page < 1) page = 1;
            } catch (NumberFormatException e) {
                page = 1;
            }
        }

        List<Book> books = bookDAO.searchBooksByTitle(keyword, page, pageSize);
        int totalBooks = bookDAO.getSearchBooksCount(keyword);
        int totalPages = (int) Math.ceil((double) totalBooks / pageSize);
        
        // 获取所有图书分类
        List<BookCategory> categories = categoryDAO.getAllCategories();
        
        // 获取推荐的分类
        List<BookCategory> recommendedCategories = categoryDAO.getRecommendedCategories();
        
        // 获取推荐分类的数量
        int recommendedCount = categoryDAO.getRecommendedCategoriesCount();

        request.setAttribute("books", books);
        request.setAttribute("currentPage", page);
        request.setAttribute("totalPages", totalPages);
        request.setAttribute("totalBooks", totalBooks);
        request.setAttribute("categories", categories);
        request.setAttribute("recommendedCategories", recommendedCategories);
        request.setAttribute("recommendedCount", recommendedCount);
        request.setAttribute("keyword", keyword);

        request.getRequestDispatcher("admin.jsp").forward(request, response);
    }

    // 编辑图书
    private void editBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int bookId = Integer.parseInt(request.getParameter("id"));
        Book book = bookDAO.getBookById(bookId);
        
        // 获取所有图书分类
        List<BookCategory> categories = categoryDAO.getAllCategories();

        request.setAttribute("book", book);
        request.setAttribute("categories", categories);
        request.setAttribute("action", "update");

        request.getRequestDispatcher("book_form.jsp").forward(request, response);
    }

    // 更新图书
    private void updateBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        double price = Double.parseDouble(request.getParameter("price"));
        String category = request.getParameter("category");
        String description = request.getParameter("description");
        int stock = Integer.parseInt(request.getParameter("stock"));

        Book book = new Book();
        book.setId(id);
        book.setTitle(title);
        book.setAuthor(author);
        book.setPrice(price);
        book.setCategory(category);
        book.setDescription(description);
        book.setStock(stock);

        if (bookDAO.updateBook(book)) {
            request.setAttribute("successMessage", "图书信息更新成功");
        } else {
            request.setAttribute("errorMessage", "图书信息更新失败");
        }

        listBooks(request, response);
    }
    
    // 列出所有订单（管理端）
    private void listOrders(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            // 获取订单号搜索参数
            String orderId = request.getParameter("orderId");
            request.setAttribute("orderId", orderId);
            
            List<Order> orders;
            int orderCount;
            double totalSalesAmount;
            
            // 如果提供了订单号，则进行完全匹配搜索
            if (orderId != null && !orderId.isEmpty()) {
                Order order = orderDAO.getOrderById(orderId);
                if (order != null) {
                    orders = new ArrayList<>();
                    orders.add(order);
                } else {
                    orders = new ArrayList<>(); // 未找到时返回空列表
                }
                orderCount = orders.size();
                totalSalesAmount = orders.stream().mapToDouble(Order::getTotalPrice).sum();
            } else {
                // 否则获取所有订单
                orders = orderDAO.getAllOrders();
                orderCount = orderDAO.getOrderCount();
                totalSalesAmount = orderDAO.getTotalSalesAmount();
            }
            
            request.setAttribute("orders", orders);
            request.setAttribute("orderCount", orderCount);
            request.setAttribute("totalSalesAmount", totalSalesAmount);
            
            // 为了在订单管理页面也能显示导航栏，保持与图书管理页面一致
            List<BookCategory> categories = categoryDAO.getAllCategories();
            List<BookCategory> recommendedCategories = categoryDAO.getRecommendedCategories();
            int recommendedCount = categoryDAO.getRecommendedCategoriesCount();
            
            request.setAttribute("categories", categories);
            request.setAttribute("recommendedCategories", recommendedCategories);
            request.setAttribute("recommendedCount", recommendedCount);
            
            request.getRequestDispatcher("admin.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("errorMessage", "获取订单列表时发生错误: " + e.getMessage());
            request.getRequestDispatcher("admin.jsp").forward(request, response);
        }
    }
    
    // 更新订单状态
    private void updateOrderStatus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String orderId = request.getParameter("orderId");
            String status = request.getParameter("status");
            
            if (orderId != null && !orderId.isEmpty() && status != null && !status.isEmpty()) {
                boolean success = orderDAO.updateOrderStatus(orderId, status);
                if (success) {
                    request.setAttribute("successMessage", "订单状态更新成功");
                } else {
                    request.setAttribute("errorMessage", "订单状态更新失败");
                }
            } else {
                request.setAttribute("errorMessage", "缺少必要参数");
            }
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("errorMessage", "更新订单状态时发生错误: " + e.getMessage());
        }
        
        // 使用自定义的方式获取所有订单，避免受orderId参数影响
        try {
            // 获取所有订单
            List<Order> orders = orderDAO.getAllOrders();
            int orderCount = orderDAO.getOrderCount();
            double totalSalesAmount = orderDAO.getTotalSalesAmount();
            
            request.setAttribute("orders", orders);
            request.setAttribute("orderCount", orderCount);
            request.setAttribute("totalSalesAmount", totalSalesAmount);
            request.setAttribute("orderId", ""); // 确保搜索框为空
            
            // 为了在订单管理页面也能显示导航栏，保持与图书管理页面一致
            List<BookCategory> categories = categoryDAO.getAllCategories();
            List<BookCategory> recommendedCategories = categoryDAO.getRecommendedCategories();
            int recommendedCount = categoryDAO.getRecommendedCategoriesCount();
            
            request.setAttribute("categories", categories);
            request.setAttribute("recommendedCategories", recommendedCategories);
            request.setAttribute("recommendedCount", recommendedCount);
            
            request.getRequestDispatcher("admin.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("errorMessage", "获取订单列表时发生错误: " + e.getMessage());
            request.getRequestDispatcher("admin.jsp").forward(request, response);
        }
    }

    // 显示添加图书表单
    private void showAddBookForm(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 获取所有图书分类
        List<BookCategory> categories = categoryDAO.getAllCategories();

        request.setAttribute("categories", categories);
        request.setAttribute("action", "save");

        request.getRequestDispatcher("book_form.jsp").forward(request, response);
    }

    // 保存新图书
    private void saveBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String title = request.getParameter("title");
        String author = request.getParameter("author");
        double price = Double.parseDouble(request.getParameter("price"));
        String category = request.getParameter("category");
        String description = request.getParameter("description");
        int stock = Integer.parseInt(request.getParameter("stock"));

        Book book = new Book();
        book.setTitle(title);
        book.setAuthor(author);
        book.setPrice(price);
        book.setCategory(category);
        book.setDescription(description);
        book.setStock(stock);
        book.setDeleted(false);

        if (bookDAO.addBook(book)) {
            request.setAttribute("successMessage", "图书添加成功");
        } else {
            request.setAttribute("errorMessage", "图书添加失败");
        }

        listBooks(request, response);
    }

    // 下架/上架图书
    private void deleteBook(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int bookId = Integer.parseInt(request.getParameter("id"));
        boolean isDeleted = "true".equals(request.getParameter("delete"));

        if (bookDAO.deleteBook(bookId, isDeleted)) {
            request.setAttribute("successMessage", isDeleted ? "图书下架成功" : "图书上架成功");
        } else {
            request.setAttribute("errorMessage", "操作失败");
        }

        // 重定向到列表页面
        response.sendRedirect("admin?action=list");
    }

    // 添加图书分类
    private void addCategory(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String categoryName = request.getParameter("categoryName");

        if (categoryDAO.getCategoryByName(categoryName) != null) {
            request.setAttribute("errorMessage", "分类已存在");
        } else if (categoryDAO.addCategory(categoryName)) {
            request.setAttribute("successMessage", "分类添加成功");
        } else {
            request.setAttribute("errorMessage", "分类添加失败");
        }

        // 获取原请求中的参数，保持页面状态
        String keyword = request.getParameter("keyword");
        if (keyword != null && !keyword.isEmpty()) {
            request.setAttribute("keyword", keyword);
            searchBooks(request, response);
        } else {
            listBooks(request, response);
        }
    }
    
    // 更新分类的推荐状态
    private void updateCategoryRecommendedStatus(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int categoryId = Integer.parseInt(request.getParameter("categoryId"));
        int isRecommended = Integer.parseInt(request.getParameter("isRecommended"));
        
        // 检查如果要设置为推荐，是否已经有5个推荐分类
        if (isRecommended == 1) {
            int currentRecommendedCount = categoryDAO.getRecommendedCategoriesCount();
            if (currentRecommendedCount >= 5) {
                request.setAttribute("errorMessage", "最多只能选择5个推荐分类");
                listBooks(request, response);
                return;
            }
        }
        
        if (categoryDAO.updateCategoryRecommendedStatus(categoryId, isRecommended)) {
            request.setAttribute("successMessage", isRecommended == 1 ? "分类推荐成功" : "取消分类推荐成功");
        } else {
            request.setAttribute("errorMessage", "操作失败");
        }
        
        listBooks(request, response);
    }
    
    // 列出用户（支持活跃用户和已注销用户）
    private void listUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String view = request.getParameter("view");
            String username = request.getParameter("username");
            int page = 1;
            int pageSize = 10;
            
            if (request.getParameter("page") != null) {
                try {
                    page = Integer.parseInt(request.getParameter("page"));
                    if (page < 1) page = 1;
                } catch (NumberFormatException e) {
                    page = 1;
                }
            }
            
            // 获取用户统计信息
            int activeUserCount = userDAO.getActiveUserCount();
            int deletedUserCount = userDAO.getDeletedUserCount();
            
            // 根据视图类型获取用户列表
            if ("deleted".equals(view)) {
                List<User> deletedUsers;
                if (username != null && !username.isEmpty()) {
                    deletedUsers = userDAO.searchDeletedUsersByUsername(username);
                } else {
                    deletedUsers = userDAO.getAllDeletedUsers();
                }
                request.setAttribute("deletedUsers", deletedUsers);
                request.setAttribute("totalPages", 1); // 简化分页
                request.setAttribute("currentPage", 1);
            } else {
                // 默认显示活跃用户
                List<User> activeUsers;
                if (username != null && !username.isEmpty()) {
                    activeUsers = userDAO.searchActiveUsersByUsername(username);
                } else {
                    activeUsers = userDAO.getAllActiveUsers();
                }
                
                // 为每个用户获取订单数量和消费金额
                for (User user : activeUsers) {
                    int orderCount = userDAO.getUserOrderCount(user.getId());
                    double totalSpent = userDAO.getUserTotalSpent(user.getId());
                    user.setOrderCount(orderCount);
                    user.setTotalSpent(totalSpent);
                }
                
                request.setAttribute("activeUsers", activeUsers);
                request.setAttribute("totalPages", 1); // 简化分页
                request.setAttribute("currentPage", 1);
            }
            
            // 设置公共属性
            request.setAttribute("action", "userList");
            request.setAttribute("view", view);
            request.setAttribute("username", username);
            request.setAttribute("activeUserCount", activeUserCount);
            request.setAttribute("deletedUserCount", deletedUserCount);
            
            // 为了在用户管理页面也能显示导航栏
            List<BookCategory> categories = categoryDAO.getAllCategories();
            List<BookCategory> recommendedCategories = categoryDAO.getRecommendedCategories();
            int recommendedCount = categoryDAO.getRecommendedCategoriesCount();
            
            request.setAttribute("categories", categories);
            request.setAttribute("recommendedCategories", recommendedCategories);
            request.setAttribute("recommendedCount", recommendedCount);
            
            request.getRequestDispatcher("admin.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("errorMessage", "获取用户列表时发生错误: " + e.getMessage());
            request.getRequestDispatcher("admin.jsp").forward(request, response);
        }
    }
    
    // 搜索用户方法移至559行，保留更完整的实现
    
    // 恢复已注销用户方法移至581行，保留更完整的实现
    
    // 列出所有已注销用户（保留但不再使用，通过listUsers处理）
    private void listDeletedUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            String keyword = request.getParameter("keyword");
            List<User> deletedUsers;
            int deletedUserCount;
            int totalUserCount = userDAO.getTotalUserCount();
            int activeUserCount = userDAO.getActiveUserCount();
            
            // 如果提供了搜索关键词，则进行搜索
            if (keyword != null && !keyword.isEmpty()) {
                deletedUsers = userDAO.searchDeletedUsersByUsername(keyword);
            } else {
                // 否则获取所有已注销用户
                deletedUsers = userDAO.getAllDeletedUsers();
            }
            
            deletedUserCount = deletedUsers.size();
            
            request.setAttribute("users", deletedUsers);
            request.setAttribute("activeUserCount", activeUserCount);
            request.setAttribute("totalUserCount", totalUserCount);
            request.setAttribute("deletedUserCount", deletedUserCount);
            request.setAttribute("viewType", "deletedUsers");
            
            // 为了在用户管理页面也能显示导航栏，保持与图书管理页面一致
            List<BookCategory> categories = categoryDAO.getAllCategories();
            List<BookCategory> recommendedCategories = categoryDAO.getRecommendedCategories();
            int recommendedCount = categoryDAO.getRecommendedCategoriesCount();
            
            request.setAttribute("categories", categories);
            request.setAttribute("recommendedCategories", recommendedCategories);
            request.setAttribute("recommendedCount", recommendedCount);
            
            request.getRequestDispatcher("admin.jsp").forward(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("errorMessage", "获取已注销用户列表时发生错误: " + e.getMessage());
            request.getRequestDispatcher("admin.jsp").forward(request, response);
        }
    }
    
    // 搜索用户
    private void searchUsers(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String keyword = request.getParameter("keyword");
        String viewType = request.getParameter("viewType");
        
        request.setAttribute("keyword", keyword);
        
        if ("deletedUsers".equals(viewType)) {
            // 搜索已注销用户
            listDeletedUsers(request, response);
        } else {
            // 默认搜索活跃用户
            listUsers(request, response);
        }
    }
    
    // 恢复已注销用户
    private void restoreUser(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            int userId = Integer.parseInt(request.getParameter("userId"));
            String password = request.getParameter("password");
            
            // 验证密码
            User user = userDAO.getUserByIdWithDeleted(userId);
            if (user != null) {
                if (user.getPassword().equals(password)) {
                    if (userDAO.restoreUser(userId)) {
                        request.setAttribute("successMessage", "用户账号恢复成功");
                        // 恢复成功后跳转到普通用户列表
                        listUsers(request, response);
                        return;
                    } else {
                        request.setAttribute("errorMessage", "用户账号恢复失败");
                    }
                } else {
                    request.setAttribute("errorMessage", "密码错误，无法恢复账号");
                }
            } else {
                request.setAttribute("errorMessage", "用户不存在");
            }
            
            // 出错后返回已注销用户列表
            listDeletedUsers(request, response);
        } catch (NumberFormatException e) {
            request.setAttribute("errorMessage", "无效的用户ID");
            listDeletedUsers(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            request.setAttribute("errorMessage", "恢复用户账号时发生错误: " + e.getMessage());
            listDeletedUsers(request, response);
        }
    }
}